<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>消息发送测试</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #0056b3;
        }
        .result {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
        }
        .success {
            border-color: #28a745;
            background-color: #d4edda;
        }
        .error {
            border-color: #dc3545;
            background-color: #f8d7da;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 5px 0;
        }
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin: 10px 0;
        }
        .quick-action-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
            text-align: left;
        }
        .quick-action-btn:hover {
            background: #218838;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="container">
            <h1>🔧 消息发送测试工具</h1>
            
            <div class="test-section">
                <h3>1. Token状态检查</h3>
                <button @click="checkTokenStatus">检查Token状态</button>
                <button @click="setNewToken">设置新Token</button>
                <div id="tokenStatus" class="result"></div>
            </div>

            <div class="test-section">
                <h3>2. 手动消息测试</h3>
                <input type="text" v-model="testMessage" placeholder="输入测试消息" value="你好，请帮我查询Python工程师职位">
                <button @click="sendTestMessage">发送测试消息</button>
                <div id="messageTestResult" class="result"></div>
            </div>

            <div class="test-section">
                <h3>3. 快捷操作测试</h3>
                <div class="quick-actions">
                    <button 
                        v-for="action in quickActions" 
                        :key="action.id"
                        class="quick-action-btn"
                        @click="handleQuickAction(action)"
                    >
                        {{ action.text }}
                    </button>
                </div>
                <div id="quickActionResult" class="result"></div>
            </div>

            <div class="test-section">
                <h3>4. 调试信息</h3>
                <button @click="showDebugInfo">显示调试信息</button>
                <div id="debugInfo" class="result"></div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref } = Vue;

        createApp({
            setup() {
                const testMessage = ref('你好，请帮我查询Python工程师职位');
                const quickActions = ref([
                    { id: 1, text: '帮我查询Python工程师职位' },
                    { id: 2, text: '帮我生成一份简历' },
                    { id: 3, text: '搜索Java开发相关职位' },
                    { id: 4, text: '查询前端工程师职位' }
                ]);

                function logResult(elementId, message, isSuccess = true) {
                    const element = document.getElementById(elementId);
                    element.textContent = message;
                    element.className = `result ${isSuccess ? 'success' : 'error'}`;
                }

                function checkTokenStatus() {
                    const token = localStorage.getItem('access_token');
                    const userId = localStorage.getItem('userid');
                    
                    let status = 'Token状态检查:\n';
                    status += `- access_token: ${token ? token.substring(0, 30) + '...' : 'null'}\n`;
                    status += `- userid: ${userId || 'null'}\n`;
                    status += `- Token长度: ${token ? token.length : 0}\n`;
                    
                    if (token) {
                        try {
                            const parts = token.split('.');
                            if (parts.length === 3) {
                                const payload = JSON.parse(atob(parts[1]));
                                status += `- Token用户ID: ${payload.user_id}\n`;
                                status += `- Token过期时间: ${new Date(payload.exp * 1000).toLocaleString()}\n`;
                                status += `- Token是否过期: ${payload.exp * 1000 < Date.now() ? '是' : '否'}\n`;
                            }
                        } catch (e) {
                            status += `- Token解析错误: ${e.message}\n`;
                        }
                    }
                    
                    logResult('tokenStatus', status, !!token);
                }

                function setNewToken() {
                    const newToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE3NjA5NTk5NjIsImlhdCI6MTc2MDM1NTE2Mn0.svAqY3LFV5iuickLSmVmAA31Mx6qNw-T2pMzClY8-u8';
                    localStorage.setItem('access_token', newToken);
                    localStorage.setItem('userid', '1');
                    logResult('tokenStatus', '新Token已设置', true);
                }

                async function sendTestMessage() {
                    const message = testMessage.value.trim();
                    if (!message) {
                        logResult('messageTestResult', '请输入测试消息', false);
                        return;
                    }

                    console.log('发送测试消息:', {
                        message: message,
                        messageLength: message.length,
                        messageType: typeof message
                    });

                    try {
                        const response = await fetch('http://127.0.0.1:8000/agent_boss/chat/', {
                            method: 'POST',
                            headers: {
                                'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                question: message,
                                session_id: 'test_message_session_' + Date.now()
                            })
                        });

                        const data = await response.json();
                        
                        let result = `消息发送测试:\n`;
                        result += `问题: ${message}\n`;
                        result += `状态码: ${response.status}\n`;
                        result += `响应: ${JSON.stringify(data, null, 2)}`;
                        
                        logResult('messageTestResult', result, response.status === 200 && data.code === 200);
                    } catch (error) {
                        let result = `消息发送失败:\n`;
                        result += `问题: ${message}\n`;
                        result += `错误: ${error.message}`;
                        
                        logResult('messageTestResult', result, false);
                    }
                }

                async function handleQuickAction(action) {
                    console.log('快捷操作点击:', {
                        action: action,
                        actionType: typeof action,
                        actionText: action.text
                    });

                    const messageText = action.text || action;
                    console.log('提取的消息文本:', {
                        messageText: messageText,
                        messageType: typeof messageText,
                        messageLength: messageText ? messageText.length : 0
                    });

                    if (!messageText || !messageText.trim()) {
                        logResult('quickActionResult', `快捷操作失败: 消息为空\n操作对象: ${JSON.stringify(action)}`, false);
                        return;
                    }

                    try {
                        const response = await fetch('http://127.0.0.1:8000/agent_boss/chat/', {
                            method: 'POST',
                            headers: {
                                'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                question: messageText,
                                session_id: 'quick_action_session_' + Date.now()
                            })
                        });

                        const data = await response.json();
                        
                        let result = `快捷操作测试:\n`;
                        result += `操作: ${action.text}\n`;
                        result += `消息: ${messageText}\n`;
                        result += `状态码: ${response.status}\n`;
                        result += `响应: ${JSON.stringify(data, null, 2)}`;
                        
                        logResult('quickActionResult', result, response.status === 200 && data.code === 200);
                    } catch (error) {
                        let result = `快捷操作失败:\n`;
                        result += `操作: ${action.text}\n`;
                        result += `消息: ${messageText}\n`;
                        result += `错误: ${error.message}`;
                        
                        logResult('quickActionResult', result, false);
                    }
                }

                function showDebugInfo() {
                    const token = localStorage.getItem('access_token');
                    const userId = localStorage.getItem('userid');
                    
                    let debug = '调试信息:\n';
                    debug += `- 当前时间: ${new Date().toLocaleString()}\n`;
                    debug += `- Token存在: ${!!token}\n`;
                    debug += `- 用户ID存在: ${!!userId}\n`;
                    debug += `- 快捷操作数量: ${quickActions.value.length}\n`;
                    debug += `- 测试消息: ${testMessage.value}\n`;
                    debug += `- 测试消息长度: ${testMessage.value.length}\n`;
                    debug += `- 测试消息类型: ${typeof testMessage.value}\n`;
                    
                    logResult('debugInfo', debug, true);
                }

                return {
                    testMessage,
                    quickActions,
                    checkTokenStatus,
                    setNewToken,
                    sendTestMessage,
                    handleQuickAction,
                    showDebugInfo
                };
            }
        }).mount('#app');

        // 页面加载时检查Token状态
        window.onload = function() {
            const checkBtn = document.querySelector('button[onclick="checkTokenStatus()"]');
            if (checkBtn) {
                checkBtn.click();
            }
        };
    </script>
</body>
</html>
